<?php

namespace addons\wwh\controller;

use think\Db;
use think\Request;
use think\Exception;

class Index extends Base
{
    /**
     * 首页
     */
    public function index()
    {
		// 只允许zh-cn和en
        $lang = $this->request->get('lang', '', 'strtolower');
        if ($lang && !in_array($lang, ['zh-cn', 'en'])) {
            $this->redirect(addon_url('wwh/index/index'), 301);
            return;
        }
		
        // 获取URL名称
        $diyname = $this->request->param('diyname/s', '');

        // 获取插件配置
        $config = get_addon_config("wwh");
        $assignConfig = [
            'product_show' => $config['product_show'] ?? 1,
            'about_show'   => $config['about_show'] ?? 1,
            'cases_show'   => $config['cases_show'] ?? 1,
            'partner_show' => $config['partner_show'] ?? 1,
            'news_show'    => $config['news_show'] ?? 1
        ];

        // 使用闭包方式批量查询
        $data = [
            // 首页Banner
            'banner' => Db::name('wwh_banner')
                ->where('lang', $this->lang)
                ->order('weigh desc')
                ->select(),

            // 首页推荐产品
            'product' => Db::name('wwh_archives')
                ->where([
                    'rec_data' => '1',
                    'status' => '1',
                    'classify' => 'product',
                    'lang' => $this->lang
                ])
                ->order('weigh desc')
                ->limit(4)
                ->select(),

            // 首页推荐产品大图
            'productBig' => Db::name('wwh_archives')
                ->where([
                    'rec_data' => '1,10',
                    'status' => '1',
                    'classify' => 'product',
                    'lang' => $this->lang
                ])
                ->order('weigh desc')
                ->limit(1)
                ->select(),  // 确保返回数组

            // 首页解决方案
            'cases' => Db::name('wwh_archives')
                ->where([
                    'rec_data' => '1',
                    'status' => '1',
                    'classify' => 'cases',
                    'lang' => $this->lang
                ])
                ->order('weigh desc')
                ->limit(3)
                ->select(),

            // 首页合作伙伴
            'partner' => Db::name('wwh_partner')
                ->where([
                    'is_rec' => '1',
                    'lang' => $this->lang
                    ])
                ->order('weigh desc')
                ->limit(18)
                ->select(),

            // 首页新闻中心
            'news' => Db::name('wwh_archives')
                ->where([
                    'rec_data' => '1',
                    'status' => '1',
                    'classify' => 'news',
                    'lang' => $this->lang
                ])
                ->order('weigh desc')
                ->limit(3)
                ->select(),

            // 公司简介
            'home' => Db::name('wwh_home')
                ->where('lang', $this->lang)
                ->limit(1)
                ->find() ?: [],

            // 当前活动栏目
            'navCur' => Db::name('wwh_column')
                ->where('diyname', $diyname)
                ->find() ?: ['classify' => 'none']
        ];

        // 批量分配变量到模板
        $this->assign(array_merge($data, $assignConfig));

        return $this->view->fetch('/index');
    }

    /**
     * 简历提交处理
     */
    public function injoin()
    {
        // token验证
        $token = $this->request->post('__token__');
        if (!$token || !\think\Validate::is($token, "token", ['__token__' => $token])) {
            return json(['code' => 0, 'msg' => __lang('Token verification failed')]);
        }

        // 获取并验证验证码
        $verify2 = $this->request->post('verify2');
        if (!captcha_check($verify2)) {
            return json(['code' => 0, 'msg' => __lang('Verification code error, please try again')]);
        }

        // 获取并处理输入数据
        $realname2 = htmlspecialchars(trim($this->request->post('realname2')), ENT_QUOTES);
        $tel2 = htmlspecialchars(trim($this->request->post('tel2')), ENT_QUOTES);
        $gangwei2 = htmlspecialchars(trim($this->request->post('gangwei2')), ENT_QUOTES);

        // 验证必填字段
        if (empty($realname2) || empty($tel2) || empty($gangwei2)) {
            return json(['code' => 0, 'msg' => __lang('Please fill in all required fields')]);
        }

        // 验证姓名格式
        if (!preg_match('/^[\p{L}\s]{2,50}$/u', $realname2)) {
            return json(['code' => 0, 'msg' => __lang('Please provide a valid name')]);
        }

        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $tel2)) {
            return json(['code' => 0, 'msg' => __lang('Please provide a valid phone number')]);
        }

        // 获取上传文件
        $file = $this->request->file('url');
        if (!$file) {
            return json(['code' => 0, 'msg' => __lang('Please upload your resume')]);
        }

        // 文件验证规则（包含MIME类型）
        $validate = [
            'size' => 10000000, // 10MB
            'ext'  => 'doc,docx,xls,xlsx,ppt,pptx,pdf',
            'type' => 'application/msword,' .
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document,' .
                'application/vnd.ms-excel,' .
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,' .
                'application/vnd.ms-powerpoint,' .
                'application/vnd.openxmlformats-officedocument.presentationml.presentation,' .
                'application/pdf'
        ];

        try {
            // 开启事务
            Db::startTrans();

            // 创建上传目录
            $uploadPath = ROOT_PATH . 'public/uploads/wwh/resume/';
            if (!is_dir($uploadPath)) {
                mkdir($uploadPath, 0755, true);
            }

            // 安全上传文件
            $info = $file->validate($validate)->rule('uniqid')->move($uploadPath);
            if (!$info) {
                throw new Exception($file->getError());
            }

            // 获取文件MIME类型进行二次验证
            $filePath = $uploadPath . $info->getSaveName();
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $filePath);
            finfo_close($finfo);

            $allowedMimes = [
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/vnd.ms-excel',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/vnd.ms-powerpoint',
                'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                'application/pdf'
            ];

            if (!in_array($mime, $allowedMimes)) {
                @unlink($filePath);
                throw new Exception(__lang('Upload file format not allowed or file too large'));
            }

            $url = '/uploads/wwh/resume/' . str_replace("\\", "/", $info->getSaveName());
            $fullUrl = $this->request->domain() . $url;

            // 准备数据
            $data = [
                'realname2' => $realname2,
                'tel2' => $tel2,
                'gangwei2' => $gangwei2,
                'url' => $url,
                'lang' => $this->lang,
                'createtime' => time()
            ];

            // 构建邮件内容
            $html = "<p><strong>".__lang('Full Name')."：</strong>{$realname2}</p>
               <p><strong>".__lang('Contact Number')."：</strong>{$tel2}</p>
               <p><strong>".__lang('Position')."：</strong>{$gangwei2}</p>
               <p><strong>".__lang('Resume')."：</strong><a href=\"{$fullUrl}\">{$fullUrl}</a></p>";

            // 获取配置
            $config = get_addon_config("wwh");
            if (empty($config['hr'])) {
                throw new Exception(__lang('Resume recipient email not configured'));
            }

            // 发送邮件
            $emailResult = \app\common\library\Email::instance()
                ->to($config['hr'])
                ->subject(__lang('Job Application Resume'))
                ->message($html)
                ->send();

            if (!$emailResult) {
                throw new Exception(__lang('Failed to send email, Please check the backend email configuration'));
            }

            // 保存到数据库
            $dbResult = Db::name('wwh_injoin')->insert($data);
            if (!$dbResult) {
                throw new Exception(__lang('Database operation failed'));
            }

            // 提交事务
            Db::commit();

            return json(['code' => 1, 'msg' => __lang('Submitted Successfully')]);

        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();

            // 删除已上传的文件
            if (isset($url) && file_exists(ROOT_PATH . 'public' . $url)) {
                @unlink(ROOT_PATH . 'public' . $url);
            }

            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 客户留言
     */
    public function message()
    {
        // token验证
        $token = $this->request->post('__token__');
        if (!$token || !\think\Validate::is($token, "token", ['__token__' => $token])) {
            return json(['code' => 0, 'msg' => __lang('Token verification failed')]);
        }

        // 验证码检查
        $verify = input("verify");
        if (!captcha_check($verify)) {
            session('captcha', null);
            return json(['code' => 0, 'msg' => __lang('Verification code error, please try again')]);
        }
        session('captcha', null);

        // 数据收集与过滤
        $data = [
            'realname'   => htmlspecialchars(trim(input('realname', ''))),
            'tel'        => htmlspecialchars(trim(input('tel', ''))),
            'email'      => htmlspecialchars(trim(input('email', ''))),
            'content'    => htmlspecialchars(trim(input('content', ''))),
            'lang'       => $this->lang,
            'createtime' => time()
        ];

        // 数据验证
        $validate = new \think\Validate([
            'realname' => 'require|max:50',
            'tel' => 'require|regex:/^1[3-9]\d{9}$/',
            'email' => 'require|email',
            'content' => 'require|max:1000'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        // 构建邮件内容
        $html = "<p><strong>".__lang('Full Name')."：</strong>".htmlspecialchars($data['realname'])."</p>
           <p><strong>".__lang('Email')."：</strong>".htmlspecialchars($data['email'])."</p>
           <p><strong>".__lang('Phone')."：</strong>".htmlspecialchars($data['tel'])."</p>
           <p><strong>".__lang('Content')."：</strong>".htmlspecialchars($data['content'])."</p>";

        // 获取配置
        $config = get_addon_config("wwh");
        $receive = $config['receive'] ?? '';

        if (empty($receive)) {
            return json(['code' => 0, 'msg' => __lang('Message recipient email not configured')]);
        }

        // 发送邮件
        $emailResult = \app\common\library\Email::instance()
            ->to($receive)
            ->subject(__lang('Customer message'))
            ->message($html)
            ->send();

        // 数据库操作
        if ($emailResult) {
            $db = Db::name('wwh_message')->insert($data);
            return json(['code' => 1, 'msg' => __lang('Submitted Successfully')]);
        }

        return json(['code' => 0, 'msg' => __lang('Failed to send email, Please check the backend email configuration')]);
    }

    /**
     * 验证码
     */
    public function verify()
    {
        $captcha = new \think\captcha\Captcha();
        //验证码过期时间（s）
        $captcha->expire =1800;
        //验证码位数
        $captcha->length = 4;
        //验证成功后是否重置
        $captcha->reset = true;
        return $captcha->entry();
    }
	
	/**
     * 语言转换
     */
	public function switch()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $lang = $this->request->post('lang', '', 'strtolower');

        // 验证语言参数
        if (!in_array($lang, ['zh-cn', 'en'])) {
            return json(['code' => 0, 'msg' => '不支持的语言']);
        }

        // 设置语言并保存到cookie
        $langValue = ($lang == 'zh-cn') ? 1 : 2;
        cookie('lang', $langValue, 3600 * 24 * 30);

        // 返回跳转URL，使用addon_url并带上参数
        $redirectUrl = addon_url('wwh/index/index') . '?lang=' . $lang;

        return json([
            'code' => 1,
            'redirect_url' => $redirectUrl
        ]);
    }

}
